import {createRouter, createWebHashHistory} from "vue-router";
import {useUserStore} from "@/store/user";
import routes from "@/router/routes";
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';

const router = createRouter({
    history: createWebHashHistory(),
    routes,
});

NProgress.configure({
    easing: 'ease', // 缓冲动画类型，可选值如'ease'、'linear'等
    showSpinner: false, // 是否显示环形进度动画
});

// 添加全局前置守卫
router.beforeEach((to, from, next) => {
    NProgress.start();
    const userStore = useUserStore();
    const token = userStore.accessToken;
    if (token) {
        if (to.path === "/login") {
            next("/dashboard");
        } else {
            next();
        }
    } else {
        const whiteList = ["/login", "/register"];
        if (whiteList.includes(to.path)) {
            next();
        } else {
            next("/login");
        }
    }
})
// 路由后置守卫
router.afterEach((to) => {
    // 设置页面标题
    const title = to.meta.title ? `${to.meta.title}` : 'Vue Admin';
    document.title = title;
    NProgress.done();
});

export default router;
